package com.henu.rescue.controller;

import com.henu.rescue.entity.Admin;
import com.henu.rescue.service.AdminService;
import com.henu.rescue.utils.Result;
import com.henu.rescue.utils.ResultEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("admin")
@Api("管理员")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("login")
    @ApiOperation("登录")
    public Result login( @RequestBody Admin admin, HttpServletRequest req){
        //System.out.println(admin);
        Admin login = adminService.login(admin);
        if(login == null){
            return new Result(ResultEnums.LOGIN_FAILED);
        }

        // 登录成功，创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("admin",login.getName());
        return new Result(ResultEnums.LOGIN_SUCCESS);
    }

    @PostMapping("register")
    @ApiOperation("注册")
    public Result register(@RequestBody Admin admin){
        try {
            Admin login = adminService.login(admin);
            if(login != null){
                return new Result(ResultEnums.REGISTER_FAILED);
            }
            adminService.register(admin);
        } catch (DuplicateKeyException e) {
            //名字重复
            return new Result(ResultEnums.USERNAME_ALREADY_EXITS);
        }
        return new Result(ResultEnums.REGISTER_SUCCESS);
    }

    @PostMapping("logout")
    @ApiOperation("退出登录")
    public Result logout(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate(); // 使当前会话无效，从而退出登录
        }
        return new Result(ResultEnums.SUCCESS);
    }

}
